
import { _decorator, Component, Node, NodePool, Prefab, instantiate } from 'cc';
const { ccclass, property, menu } = _decorator;

/**
 * Predefined variables
 * Name = PoolManager
 * DateTime = Tue Feb 22 2022 20:03:10 GMT+0800 (中国标准时间)
 * Author = ashscc
 * FileBasename = PoolManager.ts
 * FileBasenameNoExtension = PoolManager
 * URL = db://assets/script/framework/PoolManager.ts
 * ManualUrl = https://docs.cocos.com/creator/3.4/manual/en/
 *
 */

interface IDictPool {
    [name: string]: NodePool
}

// interface IDictPrefab {
//     [name: string]: Prefab
// }
 
@ccclass('PoolManager')
@menu('framework/PoolManager')
export class PoolManager extends Component {
 
    private static _nodePool: IDictPool = {}
    // private _prefabPool: IDictPrefab = {}

    public static getNode(prefab: Prefab, parent: Node){
        let node: Node = null
        const name = prefab.data.name
        // this._prefabPool[name] = prefab
        const pool = this._nodePool[name]
        if(pool){
            if(pool.size() > 0) {
                node = pool.get()
            }else {
                node = instantiate(prefab)
            }
        }else {
            this._nodePool[name] = new NodePool()
            node = instantiate(prefab)
        }
        node.parent = parent
        node.active = true
        return node
    }

    public static putNode(node: Node){
        node.parent = null
        node.active = false
        const name = node.name
        if(!this._nodePool[name]) {
            this._nodePool[name] = new NodePool()
        }
        this._nodePool[name].put(node)
    }
}

/**
 * [1] Class member could be defined like this.
 * [2] Use `property` decorator if your want the member to be serializable.
 * [3] Your initialization goes here.
 * [4] Your update function goes here.
 *
 * Learn more about scripting: https://docs.cocos.com/creator/3.4/manual/en/scripting/
 * Learn more about CCClass: https://docs.cocos.com/creator/3.4/manual/en/scripting/decorator.html
 * Learn more about life-cycle callbacks: https://docs.cocos.com/creator/3.4/manual/en/scripting/life-cycle-callbacks.html
 */
